import 'dart:ui';

import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/assets/assets.dart';
import 'package:pornhub_app/assets/styles.dart';
import 'package:pornhub_app/components/base_page/base_loading_widget.dart';
import 'package:pornhub_app/components/circle_image.dart';
import 'package:pornhub_app/components/image_view.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/components/tab_bar/custom_tab_bar.dart';
import 'package:pornhub_app/components/text_view.dart';
import 'package:pornhub_app/generate/app_image_path.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/utils/app_utils.dart';
import 'package:pornhub_app/utils/app_utils.dart';
import 'package:pornhub_app/utils/app_utils.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/events.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/utils/utils.dart';
import 'package:pornhub_app/views/search/search_controller.dart';

import '../../../components/short_widget/video_layout_button.dart';
import '../controllers/blogger_detail_controller.dart';

class BloggerDetailPage extends StatefulWidget {
  const BloggerDetailPage({super.key});

  @override
  State<BloggerDetailPage> createState() => _BloggerDetailPageState();
}

class _BloggerDetailPageState extends State<BloggerDetailPage> {
  String tag = DateTime.now().millisecondsSinceEpoch.toString();

  late BloggerDetailController controller;
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  late int userId;
  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    userId = Get.arguments["userId"];
    controller = Get.put(BloggerDetailController(userId: userId), tag: tag);
    controller.getPageDetail();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<BloggerDetailController>(
        tag: tag,
        builder: (_) {
          return Scaffold(
            backgroundColor: COLOR.color_111,
            body: controller.isLoadedData
                ? RefreshIndicator(
                    onRefresh: () async {
                      eventBus.fire(BloggerRefreshEvent(
                          controller.tabItems[controller.currentIndex.value]));
                    },
                    notificationPredicate: (notification) => true,
                    child: ExtendedNestedScrollView(
                      controller: scrollController,
                      onlyOneScrollInBody: true,
                      headerSliverBuilder: (context, innerBoxScrolled) {
                        return [
                          SliverAppBar(
                            expandedHeight:
                                308.w - ScreenUtil().statusBarHeight,
                            elevation: 0.0,
                            pinned: true,
                            toolbarHeight: 56,
                            centerTitle: true,
                            titleSpacing: 0,
                            forceElevated: false,
                            scrolledUnderElevation: 0,
                            automaticallyImplyLeading: false,
                            flexibleSpace: _buildFlexibleSpace(),
                            leading: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                Get.back();
                              },
                              child: Row(
                                children: [
                                  ImageView(
                                    src: AppImagePath.icon_back_white,
                                    width: 16.w,
                                    height: 16.w,
                                  )
                                ],
                              ).marginOnly(left: 16.w),
                            ),
                          ),
                          SliverToBoxAdapter(
                            child: Stack(
                              clipBehavior: Clip.none,
                              children: [
                                Container(
                                  width: 400.w,
                                  color: COLOR.color_111,
                                  height: 4.w,
                                ),
                                Container(
                                  padding: EdgeInsets.only(
                                    left: 14.w,
                                    right: 14.w,
                                  ),
                                  decoration: BoxDecoration(
                                      color: COLOR.hexColor("#111111"),
                                      borderRadius: BorderRadius.only(
                                          topLeft: Radius.circular(14.w),
                                          topRight: Radius.circular(14.w))),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      if (controller.blogger.value.personSign !=
                                              null &&
                                          controller.blogger.value.personSign!
                                              .isNotEmpty)
                                        Container(
                                          padding: EdgeInsets.only(top: 14.w),
                                          child: Text(
                                            "${controller.blogger.value.personSign}",
                                            maxLines: 3,
                                            textAlign: TextAlign.left,
                                            overflow: TextOverflow.ellipsis,
                                            style: kTextStyle(
                                                COLOR.color_F3F4F5,
                                                fontsize: 12.w),
                                          ),
                                        ),
                                      if (controller.bloggerFansGroup.groupId !=
                                          0)
                                        Container(
                                          width: 400.w,
                                          height: 32.w,
                                          margin: EdgeInsets.only(top: 20.w),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              if (controller
                                                      .blogger.value.newFans !=
                                                  null)
                                                Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  mainAxisSize:
                                                      MainAxisSize.max,
                                                  children: [
                                                    Container(
                                                        constraints:
                                                            BoxConstraints(
                                                                maxWidth:
                                                                    288.w),
                                                        child: Stack(
                                                          clipBehavior:
                                                              Clip.none,
                                                          children:
                                                              _buildAvatarItems(),
                                                        )),
                                                  ],
                                                ),
                                              Row(
                                                children: [
                                                  Container(
                                                    width: 80.w,
                                                    height: 24.w,
                                                    alignment: Alignment.center,
                                                    decoration: BoxDecoration(
                                                        color: COLOR.hexColor(
                                                            "#FFE1AC"),
                                                        borderRadius:
                                                            BorderRadius
                                                                .circular(6.w)),
                                                    child: Text(
                                                      "加入粉丝团",
                                                      style: kTextStyle(
                                                          COLOR.hexColor(
                                                              "#FF4900"),
                                                          fontsize: 13.w),
                                                    ),
                                                  )
                                                ],
                                              ).onOpaqueTap(() {
                                                Get.toNamed(Routes.arroundFans,
                                                    arguments: {
                                                      'tag': tag,
                                                      'userId': userId
                                                    });
                                              })
                                            ],
                                          ),
                                        ),
                                      if (controller.tabItems.isNotEmpty)
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Container(
                                              width: 322.w,
                                              height: 32,
                                              margin:
                                                  EdgeInsets.only(top: 16.w),
                                              padding: EdgeInsets.only(
                                                  left: 16.w, right: 16.w),
                                              alignment: Alignment.center,
                                              decoration: BoxDecoration(
                                                color: COLOR.color_1D1D1D,
                                                borderRadius:
                                                    BorderRadius.circular(16.w),
                                              ),
                                              child: TextFormField(
                                                controller: _controller,
                                                enabled: false,
                                                focusNode: _focusNode,
                                                textAlign: TextAlign.left,
                                                style: kTextStyle(COLOR.white,
                                                    fontsize: 12.w),
                                                decoration: InputDecoration(
                                                  prefixIcon: ImageView(
                                                    src: AppImagePath
                                                        .icons_search,
                                                    width: 13.w,
                                                    height: 13.w,
                                                  ).marginRight(8),
                                                  prefixIconConstraints:
                                                      BoxConstraints(
                                                    maxHeight: 13.w,
                                                    maxWidth: 30.w,
                                                  ),
                                                  border: InputBorder.none,
                                                  errorBorder: InputBorder.none,
                                                  focusedBorder:
                                                      InputBorder.none,
                                                  enabledBorder:
                                                      InputBorder.none,
                                                  disabledBorder:
                                                      InputBorder.none,
                                                  hintText: "搜TA的片",
                                                  contentPadding:
                                                      const EdgeInsets.only(
                                                          bottom: 15),
                                                  hintStyle: kTextStyle(
                                                      COLOR.color_8B8B98,
                                                      fontsize: 12.w),
                                                ),
                                              ),
                                            ),
                                            Text(
                                              "搜索",
                                              style: kTextStyle(COLOR.white,
                                                  fontsize: 16.w),
                                            ).paddingTop(12),
                                          ],
                                        ).marginBottom(16.w).onOpaqueTap(() {
                                          Get.toNamed(Routes.searchuserresult,
                                              arguments: {
                                                'word': controller
                                                    .blogger.value.nickName,
                                                'user_id': userId
                                              });

                                          // Get.toNamed(Routes.searchUser,arguments: {
                                          //   'user_id':userId,
                                          //   'user_name':controller.blogger.value.nickName
                                          // });
                                        }),
                                    ],
                                  ),
                                ),
                                Positioned(
                                    top: -2.w,
                                    child: Container(
                                      width: 400.w,
                                      color: COLOR.color_111,
                                      height: 4.w,
                                    ))
                              ],
                            ),
                          ),
                          if (controller.tabItems.isNotEmpty)
                            SliverPersistentHeader(
                                pinned: true,
                                delegate: _StickyTabBarDelegate(
                                    child: _buildTabBar(),
                                    controller: controller))
                        ];
                      },
                      body: Container(
                        color: COLOR.color_111,
                        child: controller.tabItems.isNotEmpty
                            ? TabBarView(
                                controller: controller.tabController,
                                children: controller.pageItems,
                              )
                            : const Column(
                                children: [
                                  NoData(
                                    tips: "空空如也～～～",
                                  )
                                ],
                              ),
                      ),
                    ),
                  )
                : const BaseLoadingWidget(),
          );
        });
  }

  _buildTabBar() {
    return CustomTabBar(
      controller.tabItems.map((e) => e).toList(),
      tabController: controller.tabController,
      onTap: (value) {
        controller.currentIndex.value = value;
      },
    );
  }

  // _buildTabBarView() {
  //   return [
  //     KeepAliveWrapper(child: ArroundVideoPage(userId: userId)),
  //     KeepAliveWrapper(
  //       child: ArroundCommunityPage(userId: userId),
  //     ),
  //     KeepAliveWrapper(
  //       child: ArroundLongVideoPage(userId: userId),
  //     ),
  //     KeepAliveWrapper(
  //       child: ArroundCompilationPage(userId: userId),
  //     ),
  //     KeepAliveWrapper(
  //       child: ArroundFansPage(userId: userId),
  //     ),
  //   ];
  // }

  _buildFlexibleSpace() {
    return FlexibleSpaceBar(
      centerTitle: true,
      collapseMode: CollapseMode.pin,
      background: Stack(
        clipBehavior: Clip.none,
        children: [
          Stack(
            clipBehavior: Clip.none,
            children: [
              SizedBox(
                width: 400.w,
                height: 308.w,
                child: controller.blogger.value.logo!.isNotEmpty
                    ? ImageView(
                        src: controller.blogger.value.logo ?? '',
                        width: 400.w,
                        height: 308.w,
                        fit: BoxFit.cover,
                      )
                    : Image.asset('assets/icon/avatar.png'),
              ),
              ClipRRect(
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
                  child: Container(
                    height: double.infinity,
                    color: COLOR.white.withOpacity(0.2),
                  ),
                ),
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: -2.w,
                child: Container(
                  height: 14.w,
                  decoration: BoxDecoration(
                      color: COLOR.color_111,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(14.w),
                          topRight: Radius.circular(14.w))),
                ),
              )
            ],
          ),
          Positioned(
              top: 112.w,
              left: 14.w,
              right: 14.w,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Stack(
                        alignment: Alignment.bottomCenter,
                        children: [
                          Obx(
                            () => ImageView(
                              src: "${controller.blogger.value.logo}",
                              width: 85.w,
                              height: 85.w,
                              fit: BoxFit.cover,
                              borderRadius: BorderRadius.circular(43.w),
                              defaultPlace: Assets.avatarplaceholer,
                            ).onTap(() {
                              // Get.toBloggerDetail(
                              //     userId: controller.blogger.value.userId ?? 0);
                            }),
                          ),
                          Obx(() => (controller.blogger.value.vipType ?? 0) >
                                      0 &&
                                  AppUtils.getVipTypeToImagePath(
                                          controller.blogger.value.vipType ?? 0)
                                      .isNotEmpty
                              ? ImageView(
                                  src: AppUtils.getVipTypeToImagePath(
                                      controller.blogger.value.vipType ?? 0),
                                  height: 17.w,
                                  fit: BoxFit.fitHeight,
                                )
                              : const SizedBox.shrink()),
                        ],
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "${controller.blogger.value.nickName}",
                            style: kTextStyle(COLOR.hexColor("#F3F4F5"),
                                weight: FontWeight.w600, fontsize: 16.w),
                          ),
                          6.verticalSpace,
                          Text(
                            "用户ID：${controller.blogger.value.userId}",
                            style: kTextStyle(COLOR.hexColor("#FFFFFF"),
                                fontsize: 11.w),
                          ),
                          6.verticalSpace,
                          Obx(() =>
                              (controller.blogger.value.chatVipType ?? 0) > 0
                                  ? Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        ImageView(
                                          src: AppImagePath.mine_mine_chat_vip,
                                          height: 17.w,
                                        ),
                                        3.horizontalSpace,
                                        TextView(
                                            text: "畅聊会员时间：${Utils.dateFmt(
                                              controller.blogger.value
                                                      .chatExpiredVip ??
                                                  "",
                                              ["yyyy", "/", "mm", "/", "dd"],
                                            )}",
                                            fontSize: 11.w,
                                            color: COLOR.white),
                                      ],
                                    )
                                  : const SizedBox.shrink()),
                        ],
                      ).marginOnly(left: 8.w)
                    ],
                  ),
                  Container(
                    height: 18.w,
                    margin: EdgeInsets.only(top: 12.w, bottom: 20.w),
                    child: Row(
                      children:
                          List.generate(controller.stringItems.length, (index) {
                        return Row(
                          children: [
                            Container(
                              alignment: Alignment.center,
                              padding: EdgeInsets.only(left: 4.w, right: 4.w),
                              decoration: BoxDecoration(
                                  borderRadius: index == 0
                                      ? BorderRadius.only(
                                          topLeft: Radius.circular(4.w),
                                          bottomLeft: Radius.circular(4.w))
                                      : index ==
                                              controller.stringItems.length - 1
                                          ? BorderRadius.only(
                                              topRight: Radius.circular(4.w),
                                              bottomRight: Radius.circular(4.w))
                                          : null,
                                  color: COLOR
                                      .hexColor("#A8BBFF")
                                      .withOpacity(0.33)),
                              child: Text(
                                controller.stringItems[index],
                                style: kTextStyle(COLOR.color_F3F4F5,
                                    fontsize: 11.w),
                              ),
                            ),
                            if (index != controller.stringItems.length - 1)
                              SizedBox(
                                width: 1.w,
                              ),
                          ],
                        );
                      }),
                    ),
                  ),
                  SizedBox(
                    width: 400.w,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Column(
                              children: [
                                Text(
                                  "${controller.blogger.value.bu}",
                                  style:
                                      kTextStyle(COLOR.white, fontsize: 13.w),
                                ),
                                Text(
                                  "粉丝",
                                  style:
                                      kTextStyle(COLOR.white, fontsize: 13.w),
                                )
                              ],
                            ).marginOnly(right: 32.w),
                            Column(
                              children: [
                                Text(
                                  "${controller.blogger.value.longVideoNum}",
                                  style:
                                      kTextStyle(COLOR.white, fontsize: 13.w),
                                ),
                                Text(
                                  "视频",
                                  style:
                                      kTextStyle(COLOR.white, fontsize: 13.w),
                                )
                              ],
                            )
                          ],
                        ),
                        Row(
                          children: [
                            Obx(() => SizedBox(
                                        width: 68.w,
                                        height: 26.w,
                                        child: Image.asset(
                                            controller.isAttention.value == true
                                                ? 'assets/player/focus_y.png'
                                                : 'assets/player/focus.png'))
                                    .onOpaqueTap(() {
                                  controller.attentionUser(userId);
                                })),
                            ImageView(
                              src: AppImagePath.arround_icon_arround_chat,
                              width: 68.w,
                              height: 26.w,
                            ).marginLeft(15.w).onOpaqueTap(() {
                              // Get.toChat(
                              //     userId: controller.blogger.value.userId ?? 0,
                              //     userNickName:
                              //         "${controller.blogger.value.nickName}");
                            })
                          ],
                        )
                      ],
                    ),
                  )
                ],
              )),
        ],
      ),
    );
  }

  _buildAvatarItems() {
    List<Widget> _widgets = [];
    var len = controller.blogger.value.newFans?.length ?? 0;
    for (int i = 0; i < len; i++) {
      _widgets.add(Positioned(
          left: (i * 20).w,
          child: Container(
            decoration: BoxDecoration(
              border: Border.all(color: COLOR.white),
              borderRadius: BorderRadius.circular(24.w),
            ),
            child: ImageView(
              src: controller.blogger.value.newFans![i],
              width: 24.w,
              height: 24.w,
              borderRadius: BorderRadius.circular(24.w),
            ),
          )));
    }
    _widgets.add(Positioned(
        left: len * 20 + 16.w,
        child: Text(
          "已有${controller.blogger.value.fansGroupNum}人加入TA的粉丝团",
          style: kTextStyle(COLOR.color_EBEBEB, fontsize: 12.w),
        ).paddingTop(4.w)));
    return _widgets;
  }
}

class _StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final CustomTabBar child;
  final BloggerDetailController controller;

  _StickyTabBarDelegate({required this.child, required this.controller});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: COLOR.color_111,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          child,
          if (["视频", "刷片", "粉丝团专属"]
              .contains(controller.currentIndexTitle.value))
            Obx(
              () => VideoLayoutButton(
                controller.layout.value,
                text: '切换',
                onTap: () {
                  controller.toogleLayout();
                  eventBus.fire(VideoLayoutEvent(controller.layout.value));
                },
              ),
            )
        ],
      ).paddingOnly(left: 14.w, right: 8.w),
    );
  }

  @override
  double get maxExtent => 44;

  @override
  double get minExtent => 44;

  @override
  bool shouldRebuild(_StickyTabBarDelegate oldDelegate) {
    return maxExtent != oldDelegate.maxExtent ||
        minExtent != oldDelegate.minExtent ||
        child != oldDelegate.child;
  }
}
